import {
  useStrict, observable, runInAction, computed, action
} from 'mobx';

import Constants from '../constants/constants';
import request from '../utils/request';

useStrict(true);

export default class Base {

  @observable itemIds = [];
  @observable itemsById = {};
  @observable page = { total: 0, current: 0, limit: 10 };
  @observable status = {
    loading: false,
    removing: false,
  };
  @observable response = {
    load: '',
    remove: ''
  }

  @computed get items() {
    return this.itemIds.map(id => this.itemsById[id]);
  }
  
  /**
   * 删除列表
   * @param {*} url 
   * @param {*} option 
   */
  @action
  async remove(url, option) {

    runInAction('开始请求', () => { 
      this.response.remove = '';
      this.status.removing = true; 
    });

    // 请求删除
    const data = await request(url, option);

    // 解析响应
    runInAction('解析响应', () => { this.response.remove = data.code; });

    runInAction('结束请求', () => { this.status.removing = false; });
  }

  /**
   * 加载列表
   * @param {*} url 
   * @param {*} option 
   */
  @action
  async load(url, option) {

    runInAction('开始请求', () => { 
      this.response.load = '';
      this.status.loading = true; 
    });

    // 请求登录
    const data = await request(url, option);
    
    // 解析响应
    runInAction('解析响应', () => {

      if (data.code == Constants.Code.SUCCESS) {

        // 清空当前列表
        this.itemIds = [];

        data.data.items.map(item => {
          this.itemIds.push(item.id);
          this.itemsById[item.id] = item;
        });
      }
      else {
        this.response.load = data.code ;
      }
    })
    
    runInAction('结束请求', () => { this.status.loading = false; });
  }
}